﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Handrise.BasicModal.Serialization;

namespace Handrise.CDCable.Business
{
    public class PermitService
    {
        private ServerExchange serverExchange = new ServerExchange();

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="userBuffer">返回的用户实体序列化后的流</param>
        /// <returns>true登录成功</returns>
        public bool Login(string userName,string password,out byte[] userBuffer)
        {
            userBuffer = null;

            //通过主站服务登录
            string receiveData = serverExchange.Login(userName, password);

            //处理数据
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(receiveData);
            //先尝试获取正确的返回结果
            XmlNode xnValue = CommonFunction.GetXmlNode(xmlDoc, "message/operation/returnValue/value");
            if (xnValue == null)
            {
                //没有正确的返回结果
                return false ;
            }

            //分析返回的内容
            XmlDocument userInfoXmlDoc = new XmlDocument();
            userInfoXmlDoc.LoadXml(xnValue.InnerText);
            XmlNode xnEnity = CommonFunction.GetXmlNode(userInfoXmlDoc, "LoginInfo");
            if (xnEnity == null)
                return false;

            User user = (User)CommonFunction.GetEntityFromXML(xnEnity, typeof(User));
            if (user == null || user.IsValid == false)
                return false;

            CompactFormatterPlus cfp = new CompactFormatterPlus();
            userBuffer = cfp.Serialize(user);
            return true;
        }
    }
}
